package com.ruoyi.platform.service.impl;

import java.util.List;
import java.util.UUID;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.platform.hknet.utils.HTTPClientUtil;
import com.ruoyi.platform.mapper.MMonitoringEquipmentMapper;
import com.ruoyi.platform.domain.MMonitoringEquipment;
import com.ruoyi.platform.hknet.auth.HikLoginUtils;
import com.ruoyi.platform.mapper.MMonitoringEquipmentMapper;
import com.ruoyi.platform.vo.task.PictureTask;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthScope;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.platform.mapper.MStoreLocationMapper;
import com.ruoyi.platform.domain.MStoreLocation;
import com.ruoyi.platform.service.IMStoreLocationService;

import javax.annotation.Resource;

/**
 * 【仓位信息】Service业务层处理
 *
 * @author dataControl
 * @date 2025-09-15
 */
@Service
public class MStoreLocationServiceImpl implements IMStoreLocationService {
    private static final Logger log = LoggerFactory.getLogger(MStoreLocationServiceImpl.class);
    @Autowired
    private MStoreLocationMapper mStoreLocationMapper;

    @Autowired
    private MMonitoringEquipmentMapper equipmentMapper;

    /**
     * 0     * 查询【仓位信息】
     *
     * @param storeLocationId 【仓位信息】主键
     * @return 【仓位信息】
     */
    @Override
    public MStoreLocation selectMStoreLocationByStoreLocationId(Long storeLocationId) {
        MStoreLocation item = mStoreLocationMapper.selectMStoreLocationByStoreLocationId(storeLocationId);
        if (item != null) {
            if (item.getEquipmentId() != null) {
                item.setEquipment(equipmentMapper.selectMMonitoringEquipmentByEquipmentId(item.getEquipmentId()));
            }
        }
        return item;
    }

    /**
     * 查询【仓位信息】列表
     *
     * @param mStoreLocation 【仓位信息】
     * @return 【仓位信息】
     */
    @Override
    public List<MStoreLocation> selectMStoreLocationList(MStoreLocation mStoreLocation) {
        return mStoreLocationMapper.selectMStoreLocationList(mStoreLocation);
    }

    /**
     * 新增【仓位信息】
     *
     * @param mStoreLocation 【仓位信息】
     * @return 结果
     */
    @Override
    public int insertMStoreLocation(MStoreLocation mStoreLocation) {
        mStoreLocation.setCreateTime(DateUtils.getNowDate());
        return mStoreLocationMapper.insertMStoreLocation(mStoreLocation);
    }

    /**
     * 修改【仓位信息】
     *
     * @param mStoreLocation 【仓位信息】
     * @return 结果
     */
    @Override
    public int updateMStoreLocation(MStoreLocation mStoreLocation) {
        mStoreLocation.setUpdateTime(DateUtils.getNowDate());
        return mStoreLocationMapper.updateMStoreLocation(mStoreLocation);
    }

    /**
     * 批量删除【仓位信息】
     *
     * @param storeLocationIds 需要删除的【仓位信息】主键
     * @return 结果
     */
    @Override
    public int deleteMStoreLocationByStoreLocationIds(Long[] storeLocationIds) {
        return mStoreLocationMapper.deleteMStoreLocationByStoreLocationIds(storeLocationIds);
    }

    /**
     * 删除【仓位信息】信息
     *
     * @param storeLocationId 【仓位信息】主键
     * @return 结果
     */
    @Override
    public int deleteMStoreLocationByStoreLocationId(Long storeLocationId) {
        return mStoreLocationMapper.deleteMStoreLocationByStoreLocationId(storeLocationId);
    }

    @Override
    public int autoTaskExec() {
        List<MStoreLocation> mStoreLocations = mStoreLocationMapper.queryAutoTaskList();
        for(MStoreLocation mStoreLocation : mStoreLocations){
            MMonitoringEquipment ep = equipmentMapper.selectMMonitoringEquipmentByEquipmentId(mStoreLocation.getEquipmentId());
            
            String ipPort = "http://" + ep.getEquipmentIp() + ":" + ep.getEquipmentChannel();
            //1、调用预置点抓图
            String ptzCtrlPicUrl = ipPort + "/ISAPI/PTZCtrl/channels/0/presets/" + mStoreLocation.getPresetId() + "/picData";
            String picDataString = HikLoginUtils.doRequest(ptzCtrlPicUrl, ep.getEquipmentUserName(), ep.getEquipmentPassword(), HTTPClientUtil.HTTP_GET, null, false);
            //2、下发规则
            String aiRuleUrl = ipPort + "/ISAPI/Intelligent/AIOpenPlatform/AIRuleConfig/task/" + UUID.randomUUID().toString() + "/channels/0/preset/" + mStoreLocation.getPresetId() + "/?format=json";
            String result = HikLoginUtils.doRequest(aiRuleUrl,ep.getEquipmentUserName(),ep.getEquipmentPassword(),HTTPClientUtil.HTTP_PUT,"{}",false);
            //3、执行图片分析任务
            String uuid = UUID.randomUUID().toString();
            String pictureTaskUrl = ipPort + "/ISAPI/Intelligent/AIOpenPlatform/pictureTask/" + uuid.toString() + "?format=json";
            UsernamePasswordCredentials creds = new UsernamePasswordCredentials(ep.getEquipmentUserName(), ep.getEquipmentPassword());
            HTTPClientUtil.client.getState().setCredentials(AuthScope.ANY, creds);
            PictureTask pictureTask = new PictureTask();
            pictureTask.setTaskID(uuid);
            pictureTask.setPictureType("binary");
            pictureTask.setEngine(1);
            
            String boundary = "---------------------------------7e13971310878";
            try {
                HTTPClientUtil.doPostwithBinaryData(pictureTaskUrl, JSONObject.toJSONString(pictureTask), "picture_analysis", picDataString, "image_data", boundary);
            }catch (Exception e){
                log.error("增加图片分析任务出错了:::" + e.getMessage());
            }
        }
        return 0;
    }
}
